import 'dart:io';

import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/core/controllers/record_controller.dart';
import 'package:oramemo/entity/upload_voice_entity.dart';
import 'package:oramemo/pages/transcription/ai_transcription/ai_transcription_logic.dart';
import 'package:oramemo/pages/transcription/transcription_router.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:oramemo/common/langs/text_key.dart';

import '../transcription_chat/screens/chat_screen.dart';
import 'helper/record_helper.dart';
import 'helper/audio_uploader.dart';
import 'helper/play_helper.dart';

class TranscriptionRecodeLogic extends GetxController {
  RecordController recordController = Get.find();
  late RecordHelper _audioRecorder;
  late PlayHelper _audioPlayer;
  late AudioUploader _audioUploader;
  String? recordedFilePath;
  bool isRecording = false;
  bool isPlaying = false;
  Duration duration = Duration.zero;
  Duration position = Duration.zero;

  @override
  void onInit() {
    _audioRecorder = RecordHelper();
    _audioPlayer = PlayHelper();
    _audioUploader = AudioUploader();
    _audioRecorder.requestPermissions();
    _audioPlayer.setupAudioPlayer((play, posit, dur) {
      isPlaying = play;
      position = posit;
      duration = dur;
      update();
    });
    super.onInit();
  }

  @override
  void onClose() {
    _audioRecorder.dispose();
    _audioPlayer.dispose();
    super.onClose();
  }

  // 检查录音权限
  Future<bool> checkPermission() async {
    if (await Permission.microphone.request().isGranted) {
      return true;
    }
    Toast.show(TextKey.transcriptionPermissionError.tr);
    return false;
  }

  startRecording() async {
    // 检查权限
    if (!await checkPermission()) {
      return;
    }

    if (!isRecording) {
      recordedFilePath = null;
      await _audioRecorder.startRecording();
      isRecording = true;
      update();
      log(TextKey.transcriptionStartRecording.tr);
    }
  }

  stopRecording() async {
    if (isRecording) {
      await Future.delayed(const Duration(milliseconds: 100));
      recordedFilePath = await _audioRecorder.stopRecording();
      if (recordedFilePath != null) {
        _audioPlayer.setSource(recordedFilePath!);
      } else {
        showToast(TextKey.transcriptionUploadError.tr);
      }
      isRecording = false;
      update();
    }
  }

  Future<void> playPause() async {
    isPlaying = await _audioPlayer.playPause(recordedFilePath!);
    update();
  }

  Future<void> uploadFile() async {
    if (recordedFilePath != null) {
      UploadVoiceEntity? res =
          await recordController.uploadVoiceRecord(File(recordedFilePath!));

      if (res?.data?.id != null) {
        AiTranscriptionLogic logic = Get.find();
        logic.requestData(page: 1);
        showSuccess(TextKey.transcriptionUploadSuccess.tr);
      } else {
        showError(TextKey.transcriptionUploadError.tr);
      }
    } else {
      showToast(TextKey.transcriptionUploadError.tr);
    }
  }
}
